const base = {}

base.sendAjaxRequest = (method, url, body=null, file=null) => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);

        xhr.responseType = 'json';

        setHeaders(xhr, body, file);
        xhr.onload = () => resolve(xhr.response)
        sendResponse(xhr)
    })


    // НИЖЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    function sendResponse(xhr) {
        if (body) {
            xhr.send(JSON.stringify(body));
        } else if(file) {
            const formData = new FormData();
            formData.append('file', file.fileData, file.fileName);
            xhr.send(formData);
        } else {
            xhr.send();
        }
    }

    function setHeaders(xhr, body, file) {
        // Устанавливаем заголовки
        
        if(body) {
            xhr.setRequestHeader('X-CSRFToken', body.token);
            xhr.setRequestHeader('Content-Type', 'application/json');
        } else if(file) {
            xhr.setRequestHeader('X-CSRFToken', file.token);
        }
    }
}

base.getCurrentDate = () => {
    // Получаем текущую дату

    const currentDate = new Date();
    const day = currentDate.getDate();
    const month = currentDate.getMonth() + 1;
    const year = currentDate.getFullYear();
    return [day, month, year];
}

base.showGraph = () => {
    // Показываем график

    function fillInSchedule(list_of_days, list_of_amounts) {
        // Заполняем график

        const data = {
            labels: list_of_days,
            datasets: [{
            label: 'Статистика',
            backgroundColor: 'rgb(255, 255, 255)',
            borderColor: 'rgb(255, 99, 132)',
            data: list_of_amounts,
            }]
        };

        const config = {
            type: 'line',
            data: data,
            options: {}
        };

        const myChart = new Chart(
            document.getElementById('myChart'),
            config
        );
    }

    function getDataForGraph() {
        // Получаем данные для графика

        const [day, month, year] = base.getCurrentDate()
        const url = document.location.origin + `/main/statistics?statistics_data=true&d=${day}&m=${month}&y=${year}`;
        base.sendAjaxRequest('GET', url)
            .then(result => {
                const list_of_days = Object.keys(result);
                const list_of_amounts = Object.values(result);
                fillInSchedule(list_of_days, list_of_amounts)
            })
    }


    // ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

    getDataForGraph();
}